package com.goldplusgold.network.lib.http;


import com.example.account.manager.AppCacheSharedPreferences;
import com.example.account.manager.ParmasKey;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2017/7/11.
 */

public class BaseOkHttpClient {
    public static OkHttpClient getInstance() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                HttpUrl originalHttpUrl = originalRequest.url();
                HttpUrl.Builder builder = originalHttpUrl.newBuilder();

//                EncodeParas(originalHttpUrl, builder);
//                addCommonParas(builder);
                HttpUrl url = builder.build();
                Request.Builder requestBuilder = originalRequest.newBuilder()
                        .url(url)
                        .addHeader("Authorization", AppCacheSharedPreferences.getCacheString(ParmasKey.token))
                        .method(originalRequest.method(), originalRequest.body());

                Request request = requestBuilder.build();
                Response response = chain.proceed(request);
                MediaType contentType = null;
                String bodyString = null;
                if (response.body() != null) {
                    contentType = response.body().contentType();
                    bodyString = response.body().string();
                }
                if (response.body() != null) {// 深坑！打印body后原ResponseBody会被清空，需要重新设置body
                    ResponseBody body = ResponseBody.create(contentType, bodyString);
                    return response.newBuilder().body(body).build();
                } else {
                    return response;
                }
            }


        });
        return httpClientBuilder.build();
    }

}